# -*- coding: utf-8 -*-

import MySQLdb
from sae.const import (MYSQL_HOST, MYSQL_HOST_S,MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB)

class DBManager:

	def __getCursor(self):
		if not hasattr(self,"_conn"):
			self._conn = MySQLdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS,MYSQL_DB, port=int(MYSQL_PORT),charset="utf8")
		cursor = self._conn.cursor()
		return cursor

	def __closeCursor(self,cursor):
		cursor.close()
		if hasattr(self,"_conn"):
			self._conn.close()
			del self._conn

	# 执行一条sql语句返回受影响行数
	def executeNonQuery(self,sql):
		cur = self.__getCursor()
		cur.execute(sql)
		rowCount = cur.rowcount
		self.__closeCursor(cur)
		return rowCount


	def execueNonQueries(self,*sqls):
		cur = self.__getCursor()
		for sql in sqls:
			cur.execute(sql)
		self.__closeCursor(cur)

	def executeQuery(self,sql):
		cur = self.__getCursor()
		cur.execute(sql)
		result = list(cur.fetchall())
		self.__closeCursor(cur)
		return result
		
	def executeQueries(self,*sqls):
		results = []
		cur = self.__getCursor()
		for sql in sqls:
			cur.execute(sql)
			results.append(list(cur.fetchall()))
		self.__closeCursor(cur)

		return results

	def executeScalar(self,sql):
		pass

	def executeProc(self,procName,args):
		results = []
		cur = self.__getCursor()
		cur.callproc(procName,args)


	